package controllers

import (
	"encoding/json"
	"new/kpg/app"
	"new/kpg/e"
	"new/models"
	"new/services"

	"github.com/gin-gonic/gin"
	"github.com/unknwon/com"
)

func GetRelation(c *gin.Context) {
	err, info, total := services.GetAllRelation()
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{"value": info, "total": total}, "查询成功")
}

// DelCustomers 删除成员
func DelRelation(c *gin.Context) {
	b, _ := c.GetRawData()
	var m map[string]string
	_ = json.Unmarshal(b, &m)
	id := com.StrTo(m["RelationCno1"]).MustInt()
	if id == -1 {
		app.INFO(c, 30001, "参数错误")
		return
	}
	err := services.DelRelation(id)
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "删除成功")
}

func UpdateRelation(c *gin.Context) {
	b, _ := c.GetRawData() //获取原始字节
	var m map[string]string
	_ = json.Unmarshal(b, &m) //将结构类型转换为json字符串
	if m["RelationCno1"] == "" {
		app.INFO(c, 30000, "参数非法")
		return
	}
	RelationCno1 := m["RelationCno1"]
	RelationCname1 := m["RelationCname1"]
	RelationCno2 := m["RelationCno2"]
	RelationCname2 := m["RelationCname2"]
	Relation_Type := m["Relation_Type"]

	if RelationCno1 == "" {
		app.INFO(c, 30000, "参数非法")
		return
	}
	err := services.UpdateRelation(models.Relation{RelationCno1, RelationCname1, RelationCno2, RelationCname2, Relation_Type})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "更新成功")
}
func AddRelation(c *gin.Context) {
	b, _ := c.GetRawData() //获取原始字节
	var m map[string]string
	_ = json.Unmarshal(b, &m) //将结构类型转换为json字符串

	RelationCno1 := m["RelationCno1"]
	RelationCname1 := m["RelationCname1"]
	RelationCno2 := m["RelationCno2"]
	RelationCname2 := m["RelationCname2"]
	Relation_Type := m["Relation_Type"]

	if RelationCno1 == "" {
		app.INFO(c, 30000, "参数非法")
		return
	}
	err := services.AddRelation(models.Relation{RelationCno1, RelationCname1, RelationCno2, RelationCname2, Relation_Type})
	if err != nil {
		app.Error(c, e.ERROR, err, err.Error())
		return
	}
	app.OK(c, map[string]interface{}{}, "添加成功")
}
